package com.harmontronics.hanma.paas.paas.domain.organization.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.OrgTree;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.OrgUserExport;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.UserSort;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.HmUserFields;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.HmUserOrgFields;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.persistence.HmUserOrgRepository;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUserOrg;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.persistence.HmUserRepository;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmOrgPO;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserPO;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.harmontronics.hanma.paas.paas.common.PageBase;

import com.harmontronics.hanma.paas.paas.domain.organization.repository.mapper.HmUserOrgMapper;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserOrgPO;
import java.util.List;

@Service("hmUserOrgService")
@DS("#header.App-Unique")
public class HmUserOrgService implements IHmUserOrgService{

    @Autowired
    private HmUserOrgRepository hmUserOrgRepository;

    @Autowired
    private HmUserOrgMapper hmUserOrgMapper;

    @Autowired
    private HmUserRepository hmUserRepository;

    @Autowired
    private HmUserOrgSerialService hmUserOrgSerialService;

    @Autowired
    private IHmOrgService hmOrgService;


    @Override
    public boolean selectUserWithOrgIds(List<Long> orgIds) {
        if (CollectionUtils.isNotEmpty(orgIds)) {
            int count = selectCount(orgIds);
            return count > 0;
        }
        return false;
    }

    private int selectCount(List<Long> orgIds) {
        List<HmUserOrgPO> userOrgList = hmUserOrgMapper.selectList(
                new QueryWrapper<HmUserOrgPO>()
                        .in(HmUserOrgFields.ORG_ID, orgIds)
                        .eq(HmUserOrgFields.DELETED, NumberEnum.ZERO.getNum()));
        if (CollectionUtils.isNotEmpty(userOrgList)) {
            List<Long> userIdList =
                    userOrgList.stream().mapToLong(HmUserOrgPO::getUserId).boxed()
                            .collect(Collectors.toList());
            List<HmUserPO> userList =
                    hmUserRepository.list(
                            new QueryWrapper<HmUserPO>()
                                    .in(HmUserFields.ID, userIdList)
                                    .eq(HmUserFields.STATUS, NumberEnum.ONE.getNum())
                                    .eq(HmUserFields.DELETED,
                                            NumberEnum.ZERO.getNum()));
            return userList.size();
        }
        return NumberEnum.ZERO.getNum();
    }

    @Override
    public List<OrgTree> selectOrgWithUserId(Long userId) {
        return hmUserOrgMapper.selectOrgWithUserId(userId);
    }

    /**
     * 同步当前用户关联的组织关系
     *
     * @param userId
     * @param orgIds
     */
    @Override
    public void updateUserOrgById(Long userId, List<Long> orgIds) {
        if (CollectionUtils.isNotEmpty(orgIds)) {
            // 1.把之前的关联关系删除
            hmUserOrgMapper.delete(
                    new UpdateWrapper<HmUserOrgPO>()
                            .eq(HmUserOrgFields.DELETED, NumberEnum.ZERO.getNum())
                            .eq(HmUserOrgFields.USER_ID, userId));

            // 2.重新建立关联关系
            List<HmUserOrgPO> userOrgList = new ArrayList<>();
            for (Long id : orgIds) {
                HmUserOrgPO userOrg = new HmUserOrgPO();
                userOrg.setUserId(userId);
                userOrg.setOrgId(id);
                userOrg.setDeleted(NumberEnum.ZERO.getNum());
                userOrgList.add(userOrg);
            }
            hmUserOrgRepository.saveBatch(userOrgList);
        }
    }

    @Override
    public void moveOrgWithUserId(List<Long> userIds, Long srcId, Long orgId) {
        // 如果一个用户在A和B部门，又把该用户从B移动到了A部门提示“该员工已经在xx部门中”
        List<HmUserOrgPO> indexUserOrgList = selectUserOrgWithUserIdOrgId(userIds, orgId);
        if (CollectionUtils.isNotEmpty(indexUserOrgList) && userIds.size() == NumberEnum.ONE
                .getNum()) {
            throw new ErrorKeyException(I18nKeyEnum.EMPLOYEE_EXIST_IN_CURRENT_ORG);
        }
        if (CollectionUtils.isNotEmpty(indexUserOrgList)) {
            indexUserOrgList.forEach(org -> userIds.remove(org.getUserId()));
        }

        List<HmUserOrgPO> userOrgList = selectUserOrgWithUserIdOrgId(userIds, srcId);
        userOrgList.forEach(org -> org.setOrgId(orgId));
        hmUserOrgRepository.updateBatchById(userOrgList);
    }

    private List<HmUserOrgPO> selectUserOrgWithUserIdOrgId(List<Long> userIds, Long orgId) {
        return hmUserOrgMapper.selectList(
                new QueryWrapper<HmUserOrgPO>()
                        .in(HmUserOrgFields.USER_ID, userIds)
                        .eq(HmUserOrgFields.ORG_ID, orgId)
                        .eq(HmUserOrgFields.DELETED, NumberEnum.ZERO.getNum()));
    }


    @Override
    public List<OrgUserExport> selectExportUserWithOrgId(long orgId, String name,
            String username, String mobile, Integer status, String email) {
        List<Long> orgIdList = hmOrgService.selectChildrenIdWithId(orgId);
        return hmUserOrgMapper
                .selectExportUserWithOrgId(orgIdList, orgId, name, username, mobile, status,
                        email);
    }


}